package org.edu.eece262.taskshare;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

public class TaskShareService extends Service {
	private static final String PREFS_NAME = "TASKSHARELOGIN";

	@Override 
	public void onCreate() {
		Log.d("TaskShareService", "OnCreate(): Scheduling self");
		AlarmManager alarm = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
		alarm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 
				AlarmManager.INTERVAL_FIFTEEN_MINUTES/30, 
				PendingIntent.getService(this, 0, new Intent(this, TaskShareService.class), 0));
	}
	
	@Override 
	public void onDestroy() {
		
	}
	
	@Override 
	public void onStart(Intent intent, int startId) {
		new Thread() {
			@Override
			public void run() {
				Log.d("TaskShareService", "onStart(): Logging in");
				SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
				try {
				if(HTTPHelp.getServiceHTTPHelp().logIn(settings.getString("user", ""), settings.getString("password", ""))) {
					Log.d("TaskShareService", "onStart(): Polling");
					HTTPHelp.getServiceHTTPHelp().pollServer(getApplicationContext());
				} else {
					Log.e("TaskShareService", "onStart(): Loggin in FAILED");
				}
				} catch(Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
		
		
	}

	@Override
	public IBinder onBind(Intent intent) {
		// Don't need binding at the moment
		return null;
	}

}
